const app = getApp();
const Api = app.globalData.Api;
const wxApi = app.globalData.wxApi;
// const wxApi = require('../../../js/wxApi');
Page({
  data: {
    winWidth: '',
    winHeight: '',
    schools: [],
    namesArr: [],
    nameNodes: [],
    searchText: '',
    showSearchList: false
  },
  onLoad (option) {
    this.init(option);
  },
  init(option) {
    this.setContentSize();
    let searchText = option.schoolName;
    this.setData({
      searchText: option.schoolName
    })
    this.loadSchools(searchText);
  },
  onReady () {
    wxApi.setNavTitle('选择学校');
  },
  onInput(e) {
    console.log(e);
    let value = e.detail.value;
    this.setData({
      searchText: value
    })
    this.loadSchools(value);
  },
  /**
   * 确认并返回
   *
   * @param {*} e
   */
  onClickSchool(e) {
    let school = e.currentTarget.dataset.school;
    let pages = getCurrentPages();
    let prePage = pages[ pages.length - 2 ];
    if (school) {
      prePage.setData({
        "user.schoolName": school.name,
        "user.schoolId": school.id
      })
    } else {
      prePage.setData({
        "user.schoolName": this.data.searchText,
        "user.schoolId": ""
      })
    }
    
    wx.navigateBack();
  },
  /**
   * 设置可视内容宽高
   *
   */
  setContentSize() {
    wxApi.getScreenSize(size => {
      console.log(size);
      this.setData({
        winWidth: size.width,
        winHeight: size.height
      })
    })
  },
  loadSchools(text) {
    this.setData({
      showSearchList: false
    })
    if (!text) {
      this.setData({
        schools: []
      })
      return;
    }
    Api.getSchools(text, (data) => {
      let schools = packSchools(text, data);
      this.setData({
        schools: schools,
        showSearchList: true
      })
    })
  }
})
function packSchools(text, data) {
  let arr = [];
  let textLen = text.length;
  for (let school of data) {
    let name = school.name;
    let address = school.concatAddress;
    let names = name.split(text);
    school.addresses = address.split(text);
    school.names = names;
    arr.push(school);
  }
  return arr;
}

